/*
 * @Author: Turump 
 * @Date: 2021-04-13 10:51:09 
 * @Last Modified by: Turump
 * @Last Modified time: 2021-04-13 11:23:07
 * 按钮点击, 发出事件
 */

import { TaskBase } from "./TaskBase";

const { ccclass, property, menu, requireComponent } = cc._decorator;

@ccclass
@menu("按钮/点击发事件")
@requireComponent(cc.Button)

export default class ButtonClickTask extends TaskBase {
    @property({ displayName: "任务支持暂停", visible:false, override:true })
    isPauseable = false;

    @property({ displayName: "不允许重复点击" })
    clickOnce = true;
    
    @property({ displayName: "自定义音效" })
    isDefineAudio = false;

    @property({ displayName: "音效", type: cc.AudioClip, visible() { return this.isDefineAudio } })
    audio: cc.AudioClip = null;

    onLoad() {
        super.onLoad();
        var clickEventHandler = new cc.Component.EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = "ButtonClickTask";// 这个是代码文件名
        clickEventHandler.handler = "callback";
        clickEventHandler.customEventData = "";

        var button = this.node.getComponent(cc.Button);
        button.clickEvents.push(clickEventHandler);
        button.interactable = false;
    }

    enableTask() {
        super.enableTask();
        this.node.getComponent(cc.Button).interactable = true;
    }

    callback(event: cc.Event.EventTouch, customEventData: any) {
        // 这里 event 是一个 Event 对象，你可以通过 event.target 取到事件的发送节点
        // 这里的 customEventData 参数就等于你之前设置的 "foobar"
        if(this.clickOnce) {
            this.node.getComponent(cc.Button).interactable = false;
        }
        this.emitDoneEvent();
        if(this.isDefineAudio && this.audio) {
            cc.audioEngine.playEffect(this.audio, false);
        }
    }

}
